//
//  RecordTableViewController.m
//  ProjectB
//
//  Created by lanou on 16/5/11.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "RecordTableViewController.h"
#import "RecordTableViewCell.h"
#import "YYCoreDataHandlerRecord.h"
#import "AddRecordTableViewController.h"
#import "RecordTableViewHeaderFooterView.h"
#import "EditGroupTableViewController.h"

@interface RecordTableViewController ()

@property (nonatomic, strong) NSMutableDictionary *dataSource;
@property (nonatomic, strong) NSMutableArray *allKeys;
@property (nonatomic, strong) NSMutableArray *records;

@property (nonatomic, assign) NSInteger section;
@property (nonatomic, strong) UISegmentedControl *titleSegment;

@end

@implementation RecordTableViewController

- (NSMutableArray *)records {
    if (!_records) {
        _records = [self.dataSource objectForKey:[self.allKeys objectAtIndex:self.section]];
    }
    return _records;
}

- (NSMutableArray *)allKeys {
    if (!_allKeys) {
        _allKeys = [[NSMutableArray alloc] init];
    }
    return _allKeys;
}

- (NSMutableDictionary *)dataSource {
    if (!_dataSource) {
        _dataSource = [[NSMutableDictionary alloc] init];
        [_dataSource setObject:[NSMutableArray array] forKey:@"全部"];
        [self.allKeys addObject:@"全部"];
        
        if (![[NSUserDefaults standardUserDefaults] objectForKey:@"group"]) {
            NSArray *groups = [[NSArray alloc] initWithObjects:@"生活", @"工作", @"纪念日", nil];
            [[NSUserDefaults standardUserDefaults] setObject:groups forKey:@"group"];
        }
        NSArray *groups = [[NSUserDefaults standardUserDefaults] objectForKey:@"group"];
        for (NSString *str in groups) {
            [_dataSource setObject:[NSMutableArray array] forKey:str];
            [self.allKeys addObject:str];
        }
        
        NSArray *array = [[YYCoreDataHandlerRecord sharedCoreDataHandler] selectAllObjects];
        for (Record *record in array) {
            if (self.titleSegment.selectedSegmentIndex == 1) {
                if ([record.recordDate compare:[NSDate date]] == NSOrderedDescending) {
                    continue;
                }
            } else if (self.titleSegment.selectedSegmentIndex == 2) {
                if ([record.recordDate compare:[NSDate date]] == NSOrderedAscending) {
                    continue;
                }
            }
            
            [[_dataSource objectForKey:@"全部"] addObject:record];
            if ([groups containsObject:record.category]) {
                [[_dataSource objectForKey:record.category] addObject:record];
            }
        }
    }
    return _dataSource;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self change];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    _section = 0;
    
    self.navigationController.navigationBar.items.firstObject.backBarButtonItem = [UIBarButtonItem createBackItem];
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    _titleSegment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"全部", @"过去", @"未来", nil]];
    _titleSegment.frame = CGRectMake(0, 0, 100, 30);
    _titleSegment.selectedSegmentIndex = 0;
    [_titleSegment addTarget:self action:@selector(change) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView = _titleSegment;
    
    self.tableView.rowHeight = 40;
    self.tableView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
    self.navigationItem.rightBarButtonItem = addItem;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"RecordTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[RecordTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"header"];
}

- (void)change {
    self.records = nil;
    self.dataSource = nil;
    self.allKeys = nil;
    self.section = 0;
    [self.tableView reloadData];
}

- (void)add {
    AddRecordTableViewController *addVC = [[AddRecordTableViewController alloc] init];
    addVC.allCategories = self.allKeys;
//    addVC.completeBlock = ^(Record *record) {
//        [[self.dataSource objectForKey:@"全部"] addObject:record];
//        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"recordDate" ascending:YES];
//        [[self.dataSource objectForKey:@"全部"] sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
//        if (![record.category isEqualToString:@"全部"]) {
//            if (![self.dataSource objectForKey:record.category]) {
//                [_dataSource setObject:[NSMutableArray arrayWithObject:record] forKey:record.category];
//            } else {
//                [[self.dataSource objectForKey:record.category] addObject:record];
//            }
//            [[self.dataSource objectForKey:record.category] sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
//        }
//        [self.tableView reloadData];
//    };
    UINavigationController *addNC = [[UINavigationController alloc] initWithRootViewController:addVC];
    [self presentViewController:addNC animated:YES completion:nil];
}

- (void)tap:(UITapGestureRecognizer *)sender {
    if (sender.view.tag - 1000 == self.section) {
        return;
    }
    
    if (sender.state == UIGestureRecognizerStateEnded) {
        self.records = [NSMutableArray array];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.section] withRowAnimation:UITableViewRowAnimationFade];
        ((UIImageView *)[self.tableView headerViewForSection:self.section].contentView.subviews.firstObject).image = [UIImage imageNamed:@"right"];
        
        self.records = nil;
        self.section = sender.view.tag - 1000;
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:self.section] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)longPress:(UILongPressGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [alert addAction:[UIAlertAction actionWithTitle:@"分组管理" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            EditGroupTableViewController *editGroupTVC = [[EditGroupTableViewController alloc] initWithStyle:UITableViewStylePlain];
            UINavigationController *editGroupNC = [[UINavigationController alloc] initWithRootViewController:editGroupTVC];
            [self presentViewController:editGroupNC animated:YES completion:nil];
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == self.section) {
        return self.records.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RecordTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    // Configure the cell...
    Record *record = [[self.dataSource objectForKey:[self.allKeys objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    cell.model = record;
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    RecordTableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    headerView.tag = 1000 + section;
    
    if (section == self.section) {
        headerView.statusImageView.image = [UIImage imageNamed:@"down"];
    } else {
        headerView.statusImageView.image = [UIImage imageNamed:@"right"];
    }
    
    headerView.categoryLabel.text = [self.allKeys objectAtIndex:section];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [headerView addGestureRecognizer:tap];
    [headerView addGestureRecognizer:longPress];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Record *record = [self.records objectAtIndex:indexPath.row];
    AddRecordTableViewController *addVC = [[AddRecordTableViewController alloc] init];
    addVC.allCategories = self.allKeys;
    addVC.record = record;
    addVC.recordTitle = record.title;
    addVC.category = record.category;
    addVC.colorName = record.backgroundColor;
    addVC.date = record.recordDate;
    addVC.isTop = record.top.boolValue;
    addVC.isRemind = record.remind.boolValue;
    addVC.other = record.other;
    [self.navigationController pushViewController:addVC animated:YES];
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    Record *record = [self.records objectAtIndex:indexPath.row];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        for (UILocalNotification *ln in [UIApplication sharedApplication].scheduledLocalNotifications) {
            if ([[ln.userInfo objectForKey:@"record"] isEqualToString:record.title]) {
                [[UIApplication sharedApplication] cancelLocalNotification:ln];
            }
        }
        [[YYCoreDataHandlerRecord sharedCoreDataHandler] deleteObjectByKey:record.title];
        [self.records removeObject:record];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
